﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CalciCompositionHelper.cs" company="">
//   
// </copyright>
// <summary>
//   The calci composition helper.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace CompositionHelper
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.ComponentModel.Composition.Hosting;
    using System.Reflection;

    using CalculatorContract;

    /// <summary>
    /// The calci composition helper.
    /// </summary>
    public class CalciCompositionHelper
    {
        #region Public Properties

        /// <summary>
        /// Gets or sets CalciPlugin.
        /// </summary>
        public ICalculator CalciPlugin { get; set; }

        /// <summary>
        /// Gets or sets CalciPlugins.
        /// </summary>
        [ImportMany(typeof(ICalculator))]
        public Lazy<ICalculator, IDictionary<string, object>>[] CalciPlugins { get; set; }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        /// The assemble calculator components.
        /// </summary>
        public void AssembleCalculatorComponents()
        {
            try
            {
                var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

                var container = new CompositionContainer(catalog);

                container.ComposeParts(this);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// Get Result method.
        /// </summary>
        /// <param name="a">
        /// The a.
        /// </param>
        /// <param name="b">
        /// The b.
        /// </param>
        /// <param name="operationType">
        /// The operation Type.
        /// </param>
        /// <returns>
        /// int type.
        /// </returns>
        public double GetResult(double a, double b, string operationType)
        {
            double result = 0;
            foreach (var cal in this.CalciPlugins)
            {
                if ((string)cal.Metadata["CalciMetaData"] == operationType)
                {
                    result = cal.Value.GetNumber(a, b);
                }
            }

            return result;
        }

        #endregion
    }
}